package com.congiya.weather;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.congiya.struts2.FrontActionSupport;
import com.cvnet.util.StringUtil;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class SearchWeatherAction extends FrontActionSupport {

	private final Log logger = LogFactory.getLog(getClass());
    /**
	 * 
	 */

	
	private WeatherRegionBO wrBO;
	
	
    public void setWrBO(WeatherRegionBO wrBO) {
		this.wrBO = wrBO;
	}

    public String weatherByRegionNameToXML() throws HttpException, IOException {
    	
		WeatherRegionVO wrVO 				= null;		
		KmaRssVO kmaVO = null;
		
    	HashMap map 						= null;
    	String resStrXml 						= null;
    	
    	HttpClient client 					= null;
    	PostMethod method 					= null;
    	
    	XStream kmaXstream = null;
    	XStream resXstream = null;
    	
    	// Request 
    	String regionName 					= StringUtil.nullToString(req.getParameter("regionName"), "강남구");    	
    	String searchWeatherURL				= "http://www.kma.go.kr/wid/queryDFSRSS.jsp";
    	String regionId						= "1168000000"; // DEFAULT : 서울시 강남구
    	
    	try {
    		
	    	logger.debug("regionName : " + regionName);
	    	System.out.println("regionName : " + regionName);
	    	
	    	map = new HashMap();
	    	map.put("regionName", regionName);
	    	
	    	//---------------------------------------------------------------------
	    	// 날씨코드 조회 - DB
	    	//---------------------------------------------------------------------
	    	wrVO = wrBO.getWeatherRegionVO(map);
	    	
	    	if(wrVO != null && wrVO.getId() != null) {
	    		regionId = wrVO.getId();
	    	} 
	  
	    	
	    	//---------------------------------------------------------------------
	    	// 기상청으로 날씨 정보 요청
	    	//---------------------------------------------------------------------
			client = new HttpClient();
		    method = new PostMethod (searchWeatherURL);
	        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	        method.addParameter(new NameValuePair("zone", regionId));	            
		    client.setTimeout(6000);
	        client.executeMethod(method);
	        
	        // 기상청 날씨 정보 파싱
	        kmaXstream = new XStream(new DomDriver());
	    	initKmaAlias(kmaXstream);
	    	kmaVO = (KmaRssVO) kmaXstream.fromXML(method.getResponseBodyAsStream());   
	    	resStrXml = kmaXstream.toXML(kmaVO);
	    	
	    	logger.debug("kmaXstream.resStrXml : " + resStrXml);
	/*    	
	    	logger.debug("kmaVO : " + kmaVO);
	    	
	    	if(kmaVO != null && kmaVO.getChannel().getItem().getDescription().getBody() != null) {    		
	    		
	    		for(KmaRssDataVO kmaDataVO : kmaVO.getChannel().getItem().getDescription().getBody()) {
		    		logger.debug(
		    				"kmaDataVO.hour : " + kmaDataVO.getHour() +
		    				", kmaDataVO.day : " + kmaDataVO.getDay() +
		    				", kmaDataVO.temp : " + kmaDataVO.getTemp() +
		    				", kmaDataVO.sky : " + kmaDataVO.getSky() +
		    				", kmaDataVO.pty : " + kmaDataVO.getPty() +
		    				", kmaDataVO.wfKor : " + kmaDataVO.getWfKor()
		    		);
	    		}
	    	}
	*/    	
	    	
	    	// 기상청 날씨정보 전달
	    	resXstream = new XStream(new DomDriver());
	    	initKmaAlias(resXstream);
	    	
	    	resStrXml = resXstream.toXML(kmaVO.getChannel().getItem());
	    	//logger.debug("resXstream.resStrXml : " + resStrXml);
	    	
    	} catch (Exception ex) {
    		
    		ex.printStackTrace();
    		logger.error(ex.toString());
    	}
    	    
        res.setContentType("text/xml;charset=utf-8");
        res.setHeader("Cache-Control", "no-cache");	    	
    	PrintWriter out = res.getWriter();
    	out.println(resStrXml);
    	out.close();
    	
    	return null;
    }

    /********************************************************************************
     * 
     * rss > channel > item > description > header, body > data > hour, day, temp ...
     * 
     * ******************************************************************************
     */
    
    
    /**
     * 
     * @param xstream
     */
	public void initKmaAlias(XStream xstream) {
		xstream.alias("rss", KmaRssVO.class);
		xstream.alias("channel", KmaRssChannelVO.class);
	    xstream.alias("item", KmaRssItemVO.class);
		xstream.alias("description", KmaRssDescriptionVO.class);
	    xstream.alias("data", KmaRssDataVO.class);
	}	
	
	public void initResAlias(XStream xstream) {
	    xstream.alias("item", KmaRssItemVO.class);
		xstream.alias("description", KmaRssDescriptionVO.class);
	    xstream.alias("data", KmaRssDataVO.class);
	}	
	
}
